package com.zyh.pool;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Author zyh
 * @Date 2024/8/12 9:15
 * @Description 线程池
 */

public class ThreadPoolDemo1 {
    //使用线程池
    public static void main(String[] args) {
        //创建减法计数器
        CountDownLatch countDownLatch = new CountDownLatch(100000);
        //记录开始时间
        long start = System.currentTimeMillis();
        //创建线程池
        ExecutorService threadPool = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 100000; i++) {
            threadPool.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName() + "正在执行");
                    countDownLatch.countDown();
                }
            });
        }
        //创建墙
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        long end = System.currentTimeMillis();
        System.out.println("总时间" + (end - start));//总时间303
        threadPool.shutdown();//等线程池中所有线程任务执行完毕才销毁  推荐使用这个
        //threadPool.shutdownNow();//不等线程池中所有线程任务执行完毕就直接销毁
    }


    //不使用线程池
    public static void main1(String[] args) {
        //创建减法计数器
        CountDownLatch countDownLatch = new CountDownLatch(100000);
        //记录开始时间
        long start = System.currentTimeMillis();
        //创建一个任务
        Runnable task = new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + "正在执行");
                countDownLatch.countDown();
            }
        };
        //创建100000个线程
        for (int i = 1; i <= 100000; i++) {
            new Thread(task, "线程" + i).start();
        }
        //创建墙
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //获取线程结束时间
        long end = System.currentTimeMillis();
        System.out.println("总时间" + (end - start));//总时间4799
    }
}
